package link

import (
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"strings"
)

func GetList() []map[string]string {
	sql := Core.Sql("fuxiaohei_links").Order("id ASC").Select()
	return Core.Db.All(sql)
}

func GetApprovedList() []map[string]string {
	sql := Core.Sql("fuxiaohei_links").Order("id ASC").Where("status = ?").Select()
	return Core.Db.All(sql, "approved")
}

func validateLinkData(data map[string]string, id string) string {
	if Rt.Validator.IsEmptyString(data["title"]) {
		return "名称必填"
	}
	if !Rt.Validator.IsURL(data["url"]) {
		return "链接格式错误"
	}
	if checkUrlExist(strings.TrimSpace(data["url"]), id) {
		return "链接重复"
	}
	return ""
}

func AddLink(data map[string]string) {
	data["title"] = strings.TrimSpace(data["title"])
	data["url"] = strings.TrimSpace(data["url"])
	sql := Core.Sql("fuxiaohei_links", "title,url,desc,add_time").Insert()
	Core.Db.Exec(sql, data["title"], data["url"], data["desc"], Rt.Time.Now())
}

func AddPendingLink(data map[string]string) {
	data["title"] = strings.TrimSpace(data["title"])
	data["url"] = strings.TrimSpace(data["url"])
	sql := Core.Sql("fuxiaohei_links", "title,url,desc,add_time,status").Insert()
	Core.Db.Exec(sql, data["title"], data["url"], data["desc"], Rt.Time.Now(), "pending")
}

func UpdateLink(id string, data map[string]string) {
	data["title"] = strings.TrimSpace(data["title"])
	data["url"] = strings.TrimSpace(data["url"])
	sql := Core.Sql("fuxiaohei_links", "title,url,desc").Where("id = ?").Update()
	Core.Db.Exec(sql, data["title"], data["url"], data["desc"], id)
}

func DeleteLink(id string) {
	sql := Core.Sql("fuxiaohei_links").Where("id = ?").Delete()
	Core.Db.Exec(sql, id)
}

func GetLinkById(id string) map[string]string {
	sql := Core.Sql("fuxiaohei_links").Where("id = ?").Select()
	return Core.Db.One(sql, id)
}

func ApproveLink(id string) {
	sql := Core.Sql("fuxiaohei_links", "status").Where("id = ?").Update()
	Core.Db.Exec(sql, "approved", id)
}

// check link url existed
func checkUrlExist(url string, id string) bool {
	sql := Core.Sql("fuxiaohei_links", "id").Where("url = ?").Select()
	data := Core.Db.One(sql, url)
	if len(data) < 1 {
		return false
	}
	if id != "" {
		if id == data["id"] {
			return false
		}
		return true
	}
	return true
}

